# -*- coding: utf-8 -*-

from keras.models import load_model
import tensorflow as tf
import esc10_input
import numpy as np
import os


# mpl.rcParams["font.sans-serif"] = [u"SimHei"]
# mpl.rcParams["axes.unicode_minus"] = False

def use_gpu():
    """Configuration for GPU"""
    from keras.backend import set_session
    # from keras.backend.tensorflow_backend import set_session
    os.environ['CUDA_VISIBLE_DEVICES'] = str(0)
    config = tf.ConfigProto()
    config.gpu_options.per_process_gpu_memory_fraction = 0.5
    config.gpu_options.allow_growth = True
    set_session(tf.InteractiveSession(config=config))


def CNN_test(test_fold, feat):
    """
    Test models using test set
    :param test_fold: test fold of 5-fold cross validation
    :param feat: which feature to use
    """
    # 读取测试数据
    _, _, test_features, test_labels = esc10_input.get_data(test_fold, feat)
    # '狗', '公鸡', '雨', '海浪', '火', '婴儿哭', '喷嚏', '时钟滴答', '直升飞机', '电锯'
    # label_dict = {
    #     '0': '狗',
    #     '1': '公鸡',
    #     '2': '雨',
    #     '3': '海浪',
    #     '4': '火',
    #     '5': '婴儿哭',
    #     '6': '喷嚏',
    #     '7': '时钟滴答',
    #     '8': '直升飞机',
    #     '9': '电锯',
    # }

    print("test_features: {}, test_labels: {}".format(len(test_features), len(test_labels)))

    # 导入训练好的模型
    model = load_model('./saved_model/cnn_{}_fold{}.h5'.format(feat, test_fold))

    # ######################################################################
    # predictions = model.predict(test_features)
    # print("特征预测概率：", predictions)
    # res = np.argmax(predictions, axis=1)
    # print(res)
    # # print("预测结果为：", label_dict[str(res[0])])
    # print("预测结果为：", label_dict[res])

    #########################################################################

    # 输出训练好的模型在测试集上的表现
    score = model.evaluate(test_features, test_labels)
    print('Test score:', score[0])
    print('Test accuracy:', score[1])

    return score[1]


if __name__ == '__main__':
    # MFCC
    # use_gpu()  # 使用GPU
    # dict_acc = {}
    # print('### [Start] Test models for ESC10 dataset #####')
    # for fold in [1, 2, 3, 4, 5]:
    #     print("## Start test fold{} models #####".format(fold))
    #     acc = CNN_test(fold, 'mfcc')
    #     dict_acc['fold{}'.format(fold)] = acc
    #     print("## Finish test fold{} models #####".format(fold))
    # dict_acc['mean'] = np.mean(list(dict_acc.values()))
    # print(dict_acc)
    # print('### [Finish] Test models finished for ESC10 dataset #####')

    use_gpu()  # 使用GPU
    dict_acc = {}
    print('### [Start] Test models for ESC10 dataset #####')
    for fold in [1, 2, 3, 4, 5]:
        print("## Start test fold{} models #####".format(fold))
        acc = CNN_test(fold, 'logmel')
        dict_acc['fold{}'.format(fold)] = acc
        print("## Finish test fold{} models #####".format(fold))
    dict_acc['mean'] = np.mean(list(dict_acc.values()))
    print(dict_acc)
    print('### [Finish] Test models finished for ESC10 dataset #####')
